package org.social.controller;

import java.util.Date;

import link.jfire.baseutil.encrypt.Md5Util;

import org.remote.game.RemoteGameServer;
import org.social.constant.WechatShopResult;
import org.social.db.bean.WechatShopOrder;
import org.social.db.cache.WechatShopOrderCache;
import org.utils.ExceptionEx;
import org.utils.RemoteUtil;

import com.alibaba.fastjson.JSONObject;
import com.sojoys.artifact.third.web.core.NettyHttpContext;
import com.xiaoleilu.hutool.log.Log;
import com.xiaoleilu.hutool.log.LogFactory;

/**
 * 微信积分商城
 * 
 * @author liu.jiang
 * @date 2018年3月19日
 */
public class WechatShopServer {
    private static final Log log = LogFactory.get(WechatShopServer.class);
    /** 验证密钥 */
    private static String key = "6e4eb065d15e673152808fa8523e6725";
    /** 同步块 */
    private static Object lock = new Object();

    /**
     * 兑换
     */
    public void exchange(NettyHttpContext ctx) {
        JSONObject rstJson = new JSONObject();
        WechatShopResult rst = WechatShopResult.SUCCESS;
        String extra = "";//额外补充说明
        try {
            String serverId = ctx.params().getString("psid");// 区服id
            int playerId = ctx.params().getIntValue("roleid");// 角色id
            int prizeid = ctx.params().getIntValue("prizeid");// 礼包id
            String orderid = ctx.params().getString("orderid");// 订单id
            int num = 1;// 每次只能兑换一个
            int time = ctx.params().getIntValue("time");// time(秒)
            String token = ctx.params().getString("token");// token
            // MD5验证
            // token= md5(psid+ roleid+ prizeid+orderid+time+key);
            String md5 = Md5Util.md5Str(serverId + String.valueOf(playerId) + String.valueOf(prizeid)+ orderid + String.valueOf(time) + key);
            log.info("---token.md5="+md5);
            if (!md5.equals(token)) {
                rst = WechatShopResult.ERR_TOKEN;// token验证失败
            } else {
                RemoteGameServer gameServer = RemoteUtil.gameSync(serverId);
                if (gameServer == null) {
                    rst = WechatShopResult.ERR_SERVER_ID;// 服务器ID异常
                } else {
                    synchronized (lock) {
                        WechatShopOrder order = WechatShopOrderCache.me().getByOrderid(orderid);
                        if (order != null && order.isSuccess()) {
                            rst = WechatShopResult.ERR_ORDER_REPEATED;// 订单重复
                        } else {
                            if (order == null) {
                                order = new WechatShopOrder(orderid, serverId, playerId, prizeid,new Date(time * 1000L), false);
                                WechatShopOrderCache.me().insertAndFlush(order);// 创建并存储新订单
                            }
                            try {
                                int r =gameServer.wechatShopExchange(orderid, playerId, prizeid,num, time);
                                rst = WechatShopResult.valueOf(r);
                                if (rst == WechatShopResult.SUCCESS) {// 游戏服操作成功
                                    order.setSuccess(true);// 修改订单状态
                                    WechatShopOrderCache.me().updateAndFlush(order);
                                }else if(r > 100){
                                    rst = WechatShopResult.ERR_GAME_HANDLE;//游戏服处理异常
                                    extra = ", errcode = "+r;
                                }
                            } catch (Exception e) {
                                rst = WechatShopResult.ERR_SERVER_CONNECT;// 服务器连接异常
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            rst = WechatShopResult.ERR_PARAMS_PARSE;// 参数解析异常
            log.error(ExceptionEx.e2s(e));
        }
        rstJson.put("errno", rst.getCode());
        rstJson.put("errmsg", rst.getMsg() + extra);
        ctx.send(rstJson.toString());
        log.info("WechatShopServer.exchange rst = " + rstJson);
    }

}
